<template>
	<div>
		<el-select
			v-model="state.coding"
			:clearable="clearable"
			:multiple="multiple"
			:disabled="isDisabled"
			:filterable="filterable"
			:placeholder="placeholder"
			@change="changeState"
			@blur="onblur()"
			@clear="onclear()"
			@focus="onfocus()"
			@visible-change="visibleChange"
			@remove-tag="removeTag()"
			style="width:100%"
			@input="change($event)"
		>
			<template v-for="(item,index) in state.options">
			<el-option
			:key="item.key"
			:label="item.value"
			:value="item.key"
			v-show="exclude.indexOf(index)==-1"
			v-if="!excludeIsKey.includes(item.key)"
			/>
			</template>
		</el-select>
	</div>
</template>
<script setup lang="ts" name="DicSelect">
import { reactive, onMounted, watch } from 'vue'
import { systemApi } from '/@/api/sys/system-api'
import { getDicObject } from '/@/utils/cacheDic'
const props = defineProps({
	modelValue: [String, Array],
	dicCode: String,
	clearable: {
		type: Boolean,
		default: () => true
	},
	multiple: {
		type: Boolean,
		default: () => false
	},
	filterable: {
		type: Boolean,
		default: () => false
	},
	placeholder: {
		type: String,
		default: () => ''
	},
	exclude: {
		type: Array,
		default: () => []
	},
	excludeIsKey: {
		type: Array,
		default: () => []
	},
	isDisabled: {
		type: Boolean,
		default: false
	},
	isDepartment: {
		type: Boolean,
		default: false
	},
	customData: {
		type: Array,
		default: () => []
	},
	isTenantSelect: {
		type: Boolean,
		default: false
	}
})
// 定义子组件向父组件传值/事件
const emit = defineEmits(['update:modelValue', 'change', 'onblur', 'onclear', 'onfocus', 'visibleChange', 'removeTag', 'input']);
const state = reactive({
	options: [] as any,
	coding: props.multiple
		? props.modelValue.split(',').filter((val: any) => {
			return val
		})
		: props.modelValue
})
if (props.isDepartment) {
	//暂未支持
} else if (props.dicCode) {
	getDicObject(props.dicCode, (val: any) => {
		state.options = val
	})
} else if (props.isTenantSelect){
	systemApi.getTenantSelect().then(data => {
		if (data && data.code === 0) {
			state.options = data.data
		}
	})
} else if (props.customData.length > 0) {
	state.options = props.customData
}
// 页面加载时
onMounted(() => {
})
const changeState = (aa: any) => {
	emit("update:modelValue", aa)
	emit('change', aa)
}
const onblur = () => {
	emit('onblur', function () {})
}
const onclear = () => {
	emit('onclear', function () {})
}
const onfocus = () => {
	emit('onfocus', function () {})
}
const visibleChange = (is: any) => {
	emit('visibleChange', is)
}
const removeTag = () => {
	emit('removeTag', function () {})
}
const change = (val: any) => {
	val = props.multiple ? val.join(',') : val
	emit('input', val)
}
watch(() => props.modelValue, (val) => {
	if (!val) {
		state.coding = null
	} else {
		state.coding = props.multiple ? val.split(',') : val
	}
})
watch(() => props.customData, (val) => {
	if (val.length > 0) {
		state.options = val
	}
})
</script>